﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Data;
using System.Configuration;
using System.Xml;
//using System.Reflection;
//using SASystem.Properties;
using SalePartial.BLL.SAServiceRef;
using System.Web.UI;
using System.Web;

namespace SalePartial.BLL
{
    public enum FileType
    {
        kModel = 1,
        kPicture,
        kDrawing,
        kDocument,
        kExcel
    }

    public enum CacheNodeImgList
    {
        kDefault = 0,
        kFolder,
        kNotCached,
        kCached
    }

    [Serializable] 
    public class CategoryVendorHelpInfo
    {
        public string cateID;
        public int vendorID;
    }

    [Serializable] 
    public class SAImageInfo
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string Descript { get; set; }
        public Byte[] ImageByte { get; set; }
        public string Path{get;set;}
        public Int32 VendorId { get; set; }
        public DateTime PublishDate { get; set; }
    }

    [Serializable] 
    public class VendorItem : Object
    {
        private VendorInfo m_vendorInfo;
        public VendorItem(VendorInfo vendorInfo)
        {
            VendorInfo = vendorInfo;
        }

        public VendorInfo VendorInfo
        {
            get { return m_vendorInfo; }
            private set { m_vendorInfo = value; }
        }

        public override string ToString()
        {
            if (m_vendorInfo != null)
            {
               return m_vendorInfo.Name;
            }
            else
            {
                return base.ToString();
            }
        }
    }

    public class StandardItem : Object
    {
        private StandardInfo m_standardInfo;
        public StandardItem(StandardInfo standardInfo)
        {
            StandardInfo = standardInfo;
        }

        public StandardInfo StandardInfo
        {
            get { return m_standardInfo; }
            private set { m_standardInfo = value; }
        }

        public override string ToString()
        {
            if (m_standardInfo != null)
            {
                return m_standardInfo.Name;
            }
            else
            {
                return base.ToString();
            }
        }
    }

    public class ConfigKeys
    {
        public readonly static string DownloadFolder = "DownloadFolder";
    }

    public class SABLL
    {
        private static SAServiceClient m_activeServiceClient;
        private static SAServiceClient GetService()
        {
            if (m_activeServiceClient == null)
            {
                m_activeServiceClient = new SAServiceClient();
            }

            try
            {
                switch (m_activeServiceClient.State)
                {
                    case System.ServiceModel.CommunicationState.Closed:
                        m_activeServiceClient = new SAServiceClient();
                        m_activeServiceClient.Open();
                        break;
                    case System.ServiceModel.CommunicationState.Closing:
                        break;
                    case System.ServiceModel.CommunicationState.Created:
                        m_activeServiceClient.Open();
                        break;
                    case System.ServiceModel.CommunicationState.Faulted:
                        m_activeServiceClient.Abort();
                        m_activeServiceClient = new SAServiceClient();
                        m_activeServiceClient.Open();
                        break;
                    case System.ServiceModel.CommunicationState.Opened:
                        //do nothing.
                        break;
                    case System.ServiceModel.CommunicationState.Opening:
                        //do nothing.
                        break;
                    default:
                        break;
                }
            }
            catch (System.Exception ex)
            {
                //SABLL.ShowErrMsg(this, @"连接服务失败！" + ex.Message);
            }
            finally
            {
                m_activeServiceClient = new SAServiceClient();
            }

            return m_activeServiceClient;
        }

        //public static string GetConfig(string configKey)
        //{
        //    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        //    KeyValueConfigurationElement element = config.AppSettings.Settings[configKey];
        //    if (element != null)
        //    {
        //        return element.Value;
        //    }
        //    else
        //        return String.Empty;
        //}

        //public static void SetConfig(string configKey, string value)
        //{
        //    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        //    KeyValueConfigurationElement element = config.AppSettings.Settings[configKey];
        //    if (element != null)
        //    {
        //        element.Value = value;
        //    }
        //    else
        //        config.AppSettings.Settings.Add(configKey, value);

        //    config.Save(ConfigurationSaveMode.Modified);
        //    ConfigurationManager.RefreshSection("appSettings");
        //}


        //public static string GetRemoteServer()
        //{
        //    string address = String.Empty;
        //    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        //    XmlDocument xmlDoc = new XmlDocument();
        //    xmlDoc.Load(config.FilePath);
        //    XmlNode node = xmlDoc.SelectSingleNode(@"//client/endpoint");
        //    if (node != null)
        //    {
        //        XmlElement endPointNode = node as XmlElement;
        //        string curAddress = endPointNode.Attributes[@"address"].Value;
        //        int idx = curAddress.IndexOf('/', 7);
        //        curAddress = curAddress.Substring(7, idx - 7);
        //        address = curAddress;
        //    }
        //    return address;
        //}

        //public static bool SetRemoteServer(string address)
        //{
        //    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        //    XmlDocument xmlDoc = new XmlDocument();
        //    xmlDoc.Load(config.FilePath);
        //    XmlNode node = xmlDoc.SelectSingleNode(@"//client/endpoint");
            
        //    if (node != null)
        //    {
        //        XmlElement endPointNode = node as XmlElement;
        //        string newAddress = String.Format(@"http://{0}/SAService/", address);
        //        endPointNode.Attributes[@"address"].Value = newAddress;
        //        xmlDoc.Save(config.FilePath);
        //    }
        //    return true;
        //}

        private static string m_lastErrMsg;

        public static List<CategoryInfo> GetRootCategories()
        {

            List<CategoryInfo> retList = new List<CategoryInfo>();
            try
            {
                CategoryInfo[] arr = GetService().GetRootCategories();

                if (arr != null)
                {
                    retList.AddRange(arr);
                }
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return retList;
        }
        
        public static List<CategoryInfo> GetSubCategories(CategoryInfo cateInfo)
        {

            List<CategoryInfo> retList = new List<CategoryInfo>();
            try
            {
                CategoryInfo[] arr = GetService().GetSubCategories(cateInfo);

                if (arr != null)
                {
                    retList.AddRange(arr);
                }
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return retList;
        }

        public static bool IsCategoryContainsFamilyFromVendor(CategoryInfo category, int vendorId, bool bIncludeSubCategory)
        {
            bool bHasFamily=true;
            try
            {

                bHasFamily = GetService().IsCategoryContainsFamilyFromVendor(category, vendorId, bIncludeSubCategory);

            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return bHasFamily;
        
        }
        
        //private static ImageList m_cateImageList;
        //private static ImageList GetCategoryImageList()
        //{
        //    if (m_cateImageList == null)
        //    {
        //        m_cateImageList = new ImageList();
        //        m_cateImageList.Images.Add(Resources.closed_folder_yellow);
        //        m_cateImageList.Images.Add(Resources.open_folder_yellow);
        //        m_cateImageList.ColorDepth = ColorDepth.Depth32Bit;
        //        m_cateImageList.ImageSize = new System.Drawing.Size(24, 24);
        //    }
        //    return m_cateImageList;
        //}

        //public static void InitCategoryTreeView(System.Windows.Forms.TreeView treeView)
        //{
        //    if (treeView == null)
        //    {
        //        return;
        //    }
        //    treeView.HideSelection = false;
        //    treeView.ImageList = GetCategoryImageList();
        //    treeView.ImageIndex = 0;
        //    treeView.SelectedImageIndex = 1;

        //    treeView.AllowDrop = true;
        //    treeView.Nodes.Clear();

        //    CategoryInfo[] cateInfos = GetService().GetRootCategories();

        //    if (cateInfos == null)
        //    {
        //        return;
        //    }

        //    for (int i = 0; i < cateInfos.Length; i++)
        //    {
        //        CategoryInfo curCateInfo = cateInfos[i];

        //        AddNodeByCategoryInfo(treeView.Nodes, curCateInfo);
        //    }

        //    treeView.ExpandAll();
        //}

        //public static void InitVendorTreeView(System.Windows.Forms.TreeView treeView)
        //{
        //    if (treeView == null)
        //    {
        //        return;
        //    }
        //    treeView.HideSelection = false;

        //    treeView.AllowDrop = true;
        //    treeView.Nodes.Clear();

        //    VendorInfo[] vendorInfos = GetService().GetAllVendors();

        //    if (vendorInfos == null)
        //    {
        //        return;
        //    }

        //    for (int i = 0; i < vendorInfos.Length; i++)
        //    {
        //        VendorInfo vendorInfo = vendorInfos[i];

        //        TreeNode newNode = treeView.Nodes.Add(vendorInfo.Name);
        //        newNode.Tag = vendorInfo;
        //        newNode.ImageIndex = 2;
        //        newNode.SelectedImageIndex = newNode.ImageIndex;
        //        //now add categories.
        //        CategoryInfo[] cateInfos = GetService().GetRootCategories();
        //        for (int j = 0; j < cateInfos.Length; j++)
        //        {
        //            CategoryInfo curCateInfo = cateInfos[j];

        //            bool bHasFamily = GetService().IsCategoryContainsFamilyFromVendor(curCateInfo, vendorInfo.VendorId, true);

        //            if (bHasFamily)
        //            {
        //                AddVendorCategoryNode(newNode, vendorInfo.VendorId, curCateInfo);
        //            }
        //        }
        //    }

        //    treeView.ExpandAll();
        //}

        //public static void AddVendorCategoryNode(System.Windows.Forms.TreeNode parentNode, int vendorId, CategoryInfo categoryInfo)
        //{
        //    if (parentNode == null)
        //    {
        //        return;
        //    }

        //    //add this node.
        //    TreeNode newNode = new TreeNode();
        //    newNode.Text = categoryInfo.Name;
        //    CategoryVendorHelpInfo cvInfo = new CategoryVendorHelpInfo();
        //    cvInfo.cateID = categoryInfo.Id.ToString();
        //    cvInfo.vendorID = vendorId;
        //    newNode.Tag = cvInfo;
        //    parentNode.Nodes.Add(newNode);

        //    CategoryInfo[] cateInfos = GetService().GetSubCategories(categoryInfo);

        //    if (cateInfos == null)
        //    {
        //        return;
        //    }

        //    for (int i = 0; i < cateInfos.Length; i++)
        //    {
        //        CategoryInfo curCateInfo = cateInfos[i];

        //        bool bHasFamily = GetService().IsCategoryContainsFamilyFromVendor(curCateInfo, vendorId, true);

        //        if (bHasFamily)
        //        {
        //            AddVendorCategoryNode(newNode, vendorId, curCateInfo);
        //        }
        //    }
        //}

        //public static void AddNodeByCategoryInfo(TreeNodeCollection nodes, CategoryInfo cateInfo)
        //{
        //    //add this node.
        //    TreeNode newNode = new TreeNode();
        //    newNode.Text = cateInfo.Name;
        //    newNode.Tag = cateInfo;
        //    nodes.Add(newNode);

        //    //add sub node.
        //    //get sub nodes.
        //    CategoryInfo[] cateInfos = GetService().GetSubCategories(cateInfo);

        //    if (cateInfos == null)
        //    {
        //        return;
        //    }

        //    foreach (CategoryInfo tempCateInfo in cateInfos)
        //    {
        //        AddNodeByCategoryInfo(newNode.Nodes, tempCateInfo);
        //    }
        //}

        //public static void InitCacheTreeView(System.Windows.Forms.TreeView treeView)
        //{
        //    if (treeView == null)
        //    {
        //        return;
        //    }
        //    treeView.HideSelection = true;
        //    treeView.CheckBoxes = true;

        //    treeView.Nodes.Clear();

        //    CategoryInfo[] cateInfos = GetService().GetRootCategories();

        //    if (cateInfos == null)
        //    {
        //        return;
        //    }

        //    for (int i = 0; i < cateInfos.Length; i++)
        //    {
        //        CategoryInfo curCateInfo = cateInfos[i];

        //        AddCacheNodeByCategoryInfo(treeView.Nodes, curCateInfo);
        //    }
        //}

        //public static void AddCacheNodeByCategoryInfo(TreeNodeCollection nodes, CategoryInfo cateInfo)
        //{
        //    //add category node.
        //    TreeNode newNode = new TreeNode();
        //    newNode.Text = cateInfo.Name;
        //    newNode.ImageIndex = (int)CacheNodeImgList.kFolder;
        //    newNode.Tag = cateInfo;
        //    nodes.Add(newNode);

        //    //add sub node.
        //    //get sub nodes.
        //    CategoryInfo[] cateInfos = GetService().GetSubCategories(cateInfo);

        //    if (cateInfos != null)
        //    {
        //        foreach (CategoryInfo tempCateInfo in cateInfos)
        //        {
        //            AddCacheNodeByCategoryInfo(newNode.Nodes, tempCateInfo);
        //        }
        //    }

        //    //add families
        //    FamilyInfo[] famInfos = GetService().GetFamiliesByCategoryId(cateInfo.Id);
        //    if (famInfos != null && famInfos.Length > 0)
        //    {
        //        foreach (FamilyInfo tempFamInfo in famInfos)
        //        {
        //            //add family node.
        //            TreeNode newFamNode = new TreeNode();
        //            newFamNode.Text = tempFamInfo.Name;
        //            if (tempFamInfo.IsCached)
        //            {
        //                newFamNode.ImageIndex = (int)CacheNodeImgList.kCached;
        //            }
        //            else
        //            {
        //                newFamNode.ImageIndex = (int)CacheNodeImgList.kNotCached;
        //            }
        //            newFamNode.Tag = tempFamInfo;
        //            newNode.Nodes.Add(newFamNode);
        //        }
        //    }
        //}

        #region help functions.

        public static bool CheckPath(string excelFilePath)
        {
            if (String.IsNullOrEmpty(excelFilePath))
            {
                //ShowInfoMsg("路径不能为空！");
                return false;
            }

            if (!File.Exists(excelFilePath))
            {
                //ShowInfoMsg(String.Format("路径{0}不存在！", excelFilePath));
                return false;
            }

            return true;
        }

        //public static string OpenFileBrowser(FileType filterType)
        //{
        //    string retFileName = String.Empty;

        //    OpenFileDialog ofd = new OpenFileDialog();

        //    string filter = GetFileFilter(filterType);
        //    if (!String.IsNullOrEmpty(filter))
        //    {
        //        ofd.Filter = filter;
        //    }

        //    ofd.RestoreDirectory = true;

        //    if (ofd.ShowDialog() == DialogResult.OK)
        //    {
        //        retFileName = ofd.FileName;
        //    }

        //    return retFileName;
        //}

        //public static string SaveFileBrowser(FileType filterType, string defaultFileName)
        //{
        //    string retFileName = String.Empty;

        //    SaveFileDialog sfd = new SaveFileDialog();
        //    sfd.RestoreDirectory = true;
        //    sfd.FileName = defaultFileName;
        //    string filter = GetFileFilter(filterType);
        //    if (!String.IsNullOrEmpty(filter))
        //    {
        //        sfd.Filter = filter;
        //    }

        //    if (sfd.ShowDialog() == DialogResult.OK)
        //    {
        //        return sfd.FileName;
        //    }

        //    return String.Empty;
        //}


        //public static string OpenFolderBrowser()
        //{
        //    string retFolderName = String.Empty;

        //    FolderBrowserDialog fbd = new FolderBrowserDialog();

        //    if (fbd.ShowDialog() == DialogResult.OK)
        //    {
        //        retFolderName = fbd.SelectedPath;
        //    }

        //    return retFolderName;
        //}

        public static string GetFileFilter(FileType type)
        {
            string retFilter = String.Empty;

            switch (type)
            {
                case FileType.kModel:
                    retFilter = "模型文件 (*.ipt; *.iam)|*.ipt;*.iam";
                    break;
                case FileType.kPicture:
                    retFilter = "图片文件 (*.jpg; *.bmp; *.gif; *.png)|*.jpg;*.bmp;*.gif;*.png";
                    break;
                case FileType.kDrawing:
                    retFilter = "二维图纸 (*.dwg)|*.dwg";
                    break;
                case FileType.kDocument:
                    retFilter = "文档文件 (*.doc; *.pdf; *.caj; *.txt; *.rar)|*.doc;*.pdf;*.caj;*.txt;*.rar|所有文件 (*.*)|*.*";
                    break;
                case FileType.kExcel:
                    retFilter = "Excel 文件 (*.xls)|*.xls";
                    break;
                default:
                    break;
            }

            return retFilter;
        }

        public static void ShowErrMsg(Page page,string errMsg)
        {
            string message = string.Format("<script language=javascript>alert('{0}');</script>", errMsg);
            
            page.ClientScript.RegisterStartupScript(page.GetType(), "script", message);

            //MessageBox.Show(errMsg, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        public static void DoAlert(Page page)
        {
            string message = string.Format("<script language=javascript>alert('{0}');</script>", m_lastErrMsg);

            page.ClientScript.RegisterStartupScript(page.GetType(), "script", message);

            //MessageBox.Show(m_lastErrMsg, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        public static void ShowInfoMsg(Page page,string infoMsg)
        {
            string message = string.Format("<script language=javascript>alert('{0}');</script>", infoMsg);

            page.ClientScript.RegisterStartupScript(page.GetType(), "script", message);


            //MessageBox.Show(infoMsg, "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        //public static DialogResult ShowConfirmMsg(string msg)
        //{
            //return MessageBox.Show(msg, "操作确认", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
        //}

        public static string GetLastErrMsg()
        {
            return m_lastErrMsg;
        }

        public static List<string> InitFileTypeComboBoxView()
        {
            List<string> fileTypeList = new List<string>();

            fileTypeList.Add("STP");
            fileTypeList.Add("IGS");
            fileTypeList.Add("DWF");
            fileTypeList.Add("SAT");
            fileTypeList.Add("IPT");

            return fileTypeList;
        }

        //public static void InitFileTypeComboBoxView(ComboBox comboBox)
        //{
        //    comboBox.Items.Add("STP");
        //    comboBox.Items.Add("IGS");
        //    comboBox.Items.Add("DWF");
        //    comboBox.Items.Add("SAT");
        //    comboBox.Items.Add("IPT");
        //    comboBox.SelectedIndex = 0;
        //}

        #endregion

        public static List<ParameterInfo> GetExcelParameters(Dictionary<string, ParameterInfo> curModelParameters, string excelFilePath)
        {
            List<ParameterInfo> tempParams = ExcelServiceMethod.GetExcelParameters(excelFilePath);

            if (tempParams == null)
            {
                m_lastErrMsg = ExcelServiceMethod.lastErrMsg;
                return null;
            }

            List<ParameterInfo> retParams = new List<ParameterInfo>();

            foreach (ParameterInfo tempInfo in tempParams)
            {
                string paramName = tempInfo.Name;
                //need to process the paramName from Excel.
                ParameterInfo excelParam = GetParameterInfo(curModelParameters, paramName);
                retParams.Add(excelParam);
            }

            return retParams;
        }

        //3)	Excel参数表格填写注意事项：
        //a)	主模型的Excel 中，设置Member 为文件名称（File Name column）。师兄的意思是不是不用选择关键字？或者说是只有Member名称作为唯一的一个关键字。用来命名每个子模型的名称。
        //b)	Excel中杜绝出现中文字符，只能出现英文字符和数字。如果有一些参数在标准文档中为中文名称，则需要将其翻译成为英文。如果有一些字符翻译不便，可以考虑使用拼音首字母缩写。
        //c)	Excel中各个参数的名称，统一标注为 “u_参数名”。

        //建模过程中可变参数问题处理，在Excel表中添加一列xx[L]: Default;min;max
        //例如：参数u_D，其取值范围为1~4，默认值取2。
        //则，Excel驱动参数表建立时，不要建立u_D参数列，而是建立u_D[L]参数列，参数值填写规范如下：u_D[L]：2;1;4
        //如果其参数是用户可手动输入的，则该参数的命名方式为：u_D[F]:2
        //
        private static ParameterInfo GetParameterInfo(Dictionary<string, ParameterInfo> curModelParameters, string excelTitle)
        {
            ParameterInfo curExcelParamInfo = new ParameterInfo();
            curExcelParamInfo.ID = Guid.NewGuid();
            curExcelParamInfo.DisplayName = String.Empty;
            curExcelParamInfo.RefKey = String.Empty;
            curExcelParamInfo.ProRefKey = String.Empty;
            curExcelParamInfo.Unit = String.Empty;
            curExcelParamInfo.Tag = String.Empty;

            if (excelTitle.Contains("Part Number [Project]"))
            {
                //part number
                curExcelParamInfo.IsCustom = false;
                curExcelParamInfo.IsKey = false;
                curExcelParamInfo.Name = "u_PartNumber";
                curExcelParamInfo.DisplayName = "Part Number";

                curExcelParamInfo.RefKey = String.Empty;
                curExcelParamInfo.ProRefKey = String.Empty;
                curExcelParamInfo.Unit = String.Empty;
                curExcelParamInfo.Value = "0";
                curExcelParamInfo.IsDriver = false;

                return curExcelParamInfo;
            }
            else if (excelTitle.Contains("Member<defaultRow>1</defaultRow><filename></filename>"))
            {
                //file name
                curExcelParamInfo.IsCustom = false;
                curExcelParamInfo.IsKey = false;
                curExcelParamInfo.Name = "u_FileName";
                curExcelParamInfo.DisplayName = "File Name";

                curExcelParamInfo.RefKey = String.Empty;
                curExcelParamInfo.ProRefKey = String.Empty;
                curExcelParamInfo.Unit = String.Empty;
                curExcelParamInfo.Value = "0";
                curExcelParamInfo.IsDriver = false;

                return curExcelParamInfo;
            }



            ParameterInfo tempModelParamInfo = null;
            bool bSpecialCol = true;

            Regex regex = null;
            Match match = null;
            //Process parameter firstly.
            //u_D[L]：2;1;4
            if (excelTitle.Contains("[L]"))
            {
                //custom parameter with limit.
                regex = new Regex(@"[\d\.]+[\;][\d\.]+[\;][\d\.]+");
                match = regex.Match(excelTitle);   //2;1;4
                if (match.Captures.Count == 1)
                {
                    string tempStr = match.Value;
                    curExcelParamInfo.Tag = tempStr;
                    curExcelParamInfo.IsCustom = true;
                    curExcelParamInfo.IsKey = true;
                }
            }
            else if (excelTitle.Contains("[F]"))
            {
                //custom parameter with free.
                regex = new Regex(@"(?<=[\:\：][\s]*)[\d\.]+"); //the number or . after : or ：
                match = regex.Match(excelTitle);   //2
                if (match.Captures.Count == 1)
                {
                    string tempStr = match.Value;
                    curExcelParamInfo.Tag = tempStr;
                    curExcelParamInfo.IsCustom = true;
                    curExcelParamInfo.IsKey = true;
                }
            }
            else if (excelTitle.Contains("<key>"))
            {
                //key column. do nothing.
                bSpecialCol = true;

            }
            else
            {
                curExcelParamInfo.Name = excelTitle;
                bSpecialCol = false;
            }

            //get the correct parameter name.
            //
            string paramName = excelTitle;

            if (bSpecialCol)
            {
                //get parameter name
                regex = new Regex(@"u_[\w_]+"); //u_D
                match = regex.Match(excelTitle);
                if (match.Captures.Count >= 1)
                {
                    paramName = match.Value;
                    if (!curModelParameters.TryGetValue(paramName, out tempModelParamInfo))
                    {
                        tempModelParamInfo = null;
                    }
                }
            }
            else
            {
                paramName = excelTitle.Trim();
                if (!curModelParameters.TryGetValue(paramName, out tempModelParamInfo))
                {
                    tempModelParamInfo = null;
                }
            }

            //copy model parameter attributes if excel parameter matches.
            //
            if (tempModelParamInfo != null)
            {
                //it is model parameter.
                curExcelParamInfo.DisplayName = excelTitle;// tempModelParamInfo.DisplayName;
                curExcelParamInfo.Name = tempModelParamInfo.Name;
                curExcelParamInfo.RefKey = tempModelParamInfo.RefKey;
                curExcelParamInfo.ProRefKey = tempModelParamInfo.ProRefKey;
                curExcelParamInfo.Unit = tempModelParamInfo.Unit;
                curExcelParamInfo.Value = tempModelParamInfo.Value;
                curExcelParamInfo.IsDriver = true;
            }
            else
            {
                curExcelParamInfo.DisplayName = paramName;// excelTitle;
                curExcelParamInfo.Name = paramName;
                curExcelParamInfo.RefKey = String.Empty;
                curExcelParamInfo.ProRefKey = String.Empty;
                curExcelParamInfo.Unit = String.Empty;
                curExcelParamInfo.Value = "0";
                curExcelParamInfo.IsDriver = false;
            }

            return curExcelParamInfo;
        }

        //public static void InitModelParametersTreeView(TreeView treeView, Dictionary<string, ParameterInfo> curModelParameters)
        //{
        //    if (treeView == null || curModelParameters == null)
        //    {
        //        return;
        //    }
        //    //treeView.HideSelection = false;
        //    treeView.Nodes.Clear();

        //    foreach (string paramName in curModelParameters.Keys)
        //    {
        //        ParameterInfo paramInfo = curModelParameters[paramName];

        //        AddTreeNode(treeView.Nodes, paramInfo);
        //    }
        //}

        //private static TreeNode AddTreeNode(TreeNodeCollection nodes, ParameterInfo paramInfo)
        //{
        //    TreeNode newNode = nodes.Add(paramInfo.Name);
        //    newNode.Tag = paramInfo;

        //    newNode.Nodes.Add("DisplayName:" + Convert.ToString(paramInfo.DisplayName));
        //    newNode.Nodes.Add("ID:" + Convert.ToString(paramInfo.ID));
        //    newNode.Nodes.Add("FamilyId:" + Convert.ToString(paramInfo.FamilyID));
        //    newNode.Nodes.Add("RefKey:" + paramInfo.RefKey);
        //    newNode.Nodes.Add("IsDriver:" + paramInfo.IsDriver.ToString());
        //    newNode.Nodes.Add("IsKey:" + paramInfo.IsKey.ToString());
        //    newNode.Nodes.Add("IsCustom:" + paramInfo.IsCustom.ToString());
        //    newNode.Nodes.Add("Tag:" + Convert.ToString(paramInfo.Tag));


        //    newNode.Nodes.Add("Unit:" + Convert.ToString(paramInfo.Unit));

        //    return newNode;
        //}

        //public static void InitExcelParametersTreeView(TreeView treeView, List<ParameterInfo> curExcelParameters)
        //{
        //    if (treeView == null || curExcelParameters == null)
        //    {
        //        return;
        //    }
        //    treeView.HideSelection = false;
        //    treeView.Nodes.Clear();

        //    foreach (ParameterInfo paramInfo in curExcelParameters)
        //    {
        //        TreeNode newNode = AddTreeNode(treeView.Nodes, paramInfo);

        //        if (paramInfo.IsDriver)
        //        {
        //            newNode.ForeColor = System.Drawing.Color.Red;
        //        }
        //    }
        //}

        //public static void InitKeyParametersGridView(DataGridView dataGridView, List<ParameterInfo> curKeyParameters)
        //{
        //    dataGridView.Rows.Clear();

        //    dataGridView.AllowUserToAddRows = true;
        //    for (int i = 0; i < curKeyParameters.Count; i++)
        //    {
        //        ParameterInfo curKeyParam = curKeyParameters[i];
        //        int newRowIndex = dataGridView.Rows.Add();
        //        DataGridViewRow newRow = dataGridView.Rows[newRowIndex];
        //        newRow.Tag = curKeyParam;
        //        newRow.Cells[0].Value = curKeyParam.Name;
        //        newRow.Cells[1].Value = curKeyParam.DisplayName;
        //        DataGridViewCheckBoxCell curCheckBoxCell = (DataGridViewCheckBoxCell)newRow.Cells[2];
        //        if (!curKeyParam.IsDriver)
        //        {
        //            curCheckBoxCell.Value = false;
        //            curCheckBoxCell.ReadOnly = true;
        //            curCheckBoxCell.Style.BackColor = Color.LightGray;
        //            newRow.Cells[3].ReadOnly = true;
        //            newRow.Cells[3].Style.BackColor = curCheckBoxCell.Style.BackColor;
        //        }
        //        else
        //        {
        //            newRow.Cells[0].Style.ForeColor = Color.Red;
        //            curCheckBoxCell.Value = curKeyParam.IsCustom;
        //            curCheckBoxCell.ReadOnly = false;
        //            newRow.Cells[3].ReadOnly = false;
        //        }
        //        //dataGridView.ClearSelection();
        //        //newRow.Selected = true;
        //    }
        //    dataGridView.AllowUserToAddRows = false;

        //}

        //public static bool InitFamilyTableGridView(DataGridView dataGridView, string m_curExcelPath)
        //{
        //    if (dataGridView == null)
        //    {
        //        m_lastErrMsg = "DataGridView控件不能为Null！";
        //        return false;
        //    }

        //    dataGridView.DataSource = new DataTable();
        //    Application.DoEvents();

        //    DataTable dt = ExcelServiceMethod.GetExcelTable(m_curExcelPath);

        //    if (dt == null)
        //    {
        //        m_lastErrMsg = ExcelServiceMethod.lastErrMsg;
        //        return false;
        //    }

        //    dataGridView.DataSource = dt;

        //    return true;
        //}

        //public static bool InitFamilyTableGridView(DataGridView dataGridView, Guid familyId)
        //{
        //    if (dataGridView == null)
        //    {
        //        m_lastErrMsg = "DataGridView控件不能为Null！";
        //        return false;
        //    }

        //    dataGridView.DataSource = new DataTable();
        //    Application.DoEvents();

        //    ParameterValueInfo[] temp = new ParameterValueInfo[0];

        //     DataTable dt = null;

        //    try
        //    {
        //       dt = GetService().GetSubFamilyTable(familyId, temp);
        //       dataGridView.DataSource = dt;
        //    }
        //    catch (System.Exception ex)
        //    {
        //         m_lastErrMsg = ex.Message;
        //    }

        //    return true;
        //}

        public static Byte[] GetBinaryByPath(string filePath)
        {
            if (String.IsNullOrEmpty(filePath) || !System.IO.File.Exists(filePath))
            {
                return new Byte[0];
            }

            System.IO.FileStream fs = new System.IO.FileStream(filePath, FileMode.Open, FileAccess.Read);

            Byte[] retBuffer = new Byte[fs.Length];
            fs.Read(retBuffer, 0, (int)(fs.Length));

            return retBuffer;
        }

        public static string SaveBinaryByPath(string filePath, byte[] bytes)
        {
            if (bytes.Length == 0)
            {
                return String.Empty;
            }

            //create folder if not exist.
            string folder = System.IO.Path.GetDirectoryName(filePath);
            if (!System.IO.Directory.Exists(folder))
            {
                System.IO.Directory.CreateDirectory(folder);
            }

            System.IO.FileStream fs = new System.IO.FileStream(filePath, FileMode.Create, FileAccess.ReadWrite);
            fs.Write(bytes, 0, (int)(bytes.Length));
            fs.Close();
            return filePath;
        }

        public static bool DownLoadWebBinary(Page page,string filenm,byte[] bytes)
        {
            try
            {
                //远程下载文件 小文件
                page.Response.ClearContent();
                page.Response.ClearHeaders();
                page.Response.ContentType = "application/octet-stream";
                page.Response.AddHeader("Content-Disposition", "attachment; filename=" + filenm);
                HttpContext.Current.Response.BinaryWrite(bytes);
                page.Response.Flush();
                page.Response.Close();
            }
            catch (Exception)
            {
            }
            return true;
        }
        //public static DataGridViewRow GetSelectedRow(DataGridView curGridView)
        //{
        //    DataGridViewRow selectedRow = null;

        //    if (curGridView.SelectedRows.Count != 0)
        //    {
        //        //select row.
        //        selectedRow = curGridView.SelectedRows[0];
        //    }
        //    else
        //    {
        //        //select cell.
        //        if (curGridView.SelectedCells.Count != 0)
        //        {
        //            DataGridViewCell selectedCell = curGridView.SelectedCells[0];
        //            if (selectedCell != null)
        //            {
        //                selectedRow = curGridView.Rows[selectedCell.RowIndex];
        //            }
        //        }
        //    }

        //    return selectedRow;
        //}

        public static bool CheckTag(string tag)
        {

            //empty, or default number "2", or default range number. "2;1;10"
            if (String.IsNullOrEmpty(tag))
            {
                return true;
            }

            Regex regex = null;
            Match match = null;

            if (tag.Contains(';'))
            {
                //custom parameter with limit.
                regex = new Regex(@"^[\d\.]+[\;][\d\.]+[\;][\d\.]+$");
                match = regex.Match(tag);   //2;1;4
                if (match.Captures.Count == 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                //custom parameter with free.
                regex = new Regex(@"^[\d\.]+$");
                match = regex.Match(tag);   //2
                if (match.Captures.Count == 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        //public static void InitFamilyListView(ListView listView, List<FamilyInfo> families)
        //{
        //    if (listView == null) return;
            
        //    listView.Clear();

        //    if (families == null || families.Count == 0)
        //    {
        //        return;
        //    }

        //    ImageList myList = new ImageList();
        //    myList.ColorDepth = ColorDepth.Depth32Bit;
        //    myList.ImageSize = new Size((int)(40*1.5), (int)(30*1.5));
        //    Image defaultImage = System.Drawing.Image.FromHbitmap(Resources.partThumbnail.GetHbitmap());
        //    myList.Images.Add(defaultImage);

        //    listView.LargeImageList = myList;
        //    int curImgIdx = 0;

        //    for (int i = 0; i < 1; i++)
        //    {
        //        foreach (FamilyInfo item in families)
        //        {
        //            ListViewItem newItem = listView.Items.Add(item.DisplayName);
        //            Byte[] thumbnailPic = GetService().GetFamilyThumbnailPic(item.ID);
        //            if (thumbnailPic.Length > 0)
        //            {
        //                myList.Images.Add(System.Drawing.Image.FromStream(new MemoryStream(thumbnailPic)));
        //                curImgIdx++;
        //                newItem.ImageIndex = curImgIdx;
        //            }
        //            else
        //                newItem.ImageIndex = 0;

        //            if (i % 2 == 0)
        //            {
        //                // newItem.BackColor = System.Drawing.Color.Red;
        //            }
        //            newItem.Tag = item;
        //        }
        //    }
        //}

        //public static ListViewItem GetSelectedListItem(ListView listView)
        //{
        //    ListViewItem retItem = null;
        //    if (listView != null)
        //    {
        //        if (listView.SelectedItems != null && listView.SelectedItems.Count > 0)
        //        {
        //            retItem = listView.SelectedItems[0];
        //        }
        //    }

        //    return retItem;
        //}

        public static bool GetLimits(string expression, out double lowLimit, out double upLimit)
        {
            Regex regex = null;
            MatchCollection matchCol = null;
            lowLimit = 0;
            upLimit = 0;
            regex = new Regex(@"[\d\.]+");
            matchCol = regex.Matches(expression);
            if (matchCol.Count != 3)
                return false;

            lowLimit = Convert.ToDouble(matchCol[1].Value);
            upLimit = Convert.ToDouble(matchCol[2].Value);

            return true;
        }

        public static bool GetDefault(string expression, out double dDefault)
        {
            Regex regex = null;
            MatchCollection matchCol = null;
            dDefault = 0;
            regex = new Regex(@"[\d\.]+");
            matchCol = regex.Matches(expression);
            if (matchCol.Count == 0)
                return false;

            dDefault = Convert.ToDouble(matchCol[0].Value);
            return true;
        }

        public static string GetLocalCacheFolder(string familyId)
        {
            string retPath;
            retPath = System.IO.Path.GetTempPath();
            retPath = System.IO.Path.Combine(retPath, familyId);
            return retPath;
        }

        //public static bool SelectNode(TreeView treeView, Guid categoryId)
        //{
        //    if (treeView == null)
        //    {
        //        return false;
        //    }

        //    foreach (TreeNode item in treeView.Nodes)
        //    {
        //        TreeNode tempNode = FindNode(item, categoryId);
        //        if (tempNode != null)
        //        {
        //            treeView.SelectedNode = tempNode;
        //            return true;
        //        }
        //    }

        //    return false;
        //}

        //private static TreeNode FindNode(TreeNode treeNode, Guid categoryId)
        //{
        //    CategoryInfo categoryInfo = treeNode.Tag as CategoryInfo;

        //    if (categoryInfo == null)
        //    {
        //        return null;
        //    }

        //    if (categoryInfo.Id == categoryId)
        //    {
        //        return treeNode;
        //    }

        //    if (treeNode.Nodes.Count > 0)
        //    {
        //        foreach (TreeNode node in treeNode.Nodes)
        //        {
        //            TreeNode tempNode = FindNode(node, categoryId);
        //            if (tempNode != null)
        //            {
        //                return tempNode;
        //            }
        //        }
        //    }

        //    return null;
        //}

        public static bool PublishFamily(FamilyInfo familyInfo, FamilyAttrInfo familyAttrInfo, FamilyTableInfo familyTableInfo)
        {
            bool success = false;
            try
            {
                success = GetService().PublishFamily(familyInfo, familyAttrInfo, familyTableInfo);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return success;
        }

        public static bool UpdateFamily(FamilyInfo familyInfo, FamilyAttrInfo familyAttrInfo, FamilyTableInfo familyTableInfo)
        {
            bool success = false;

            try
            {
                success = GetService().UpdateFamily(familyInfo, familyAttrInfo, familyTableInfo);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return success;
        }

        public static bool DeleteFamily(Guid familyId)
        {
            bool success = false;

            try
            {
                success = GetService().DeleteFamily(familyId);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return success;
        }

        public static List<FamilyInfo> SearchFamilies(string searchString)
        {

            List<FamilyInfo> retList = new List<FamilyInfo>();
            try
            {
                FamilyInfo[] arr = GetService().SearchFamilies(searchString);

                if (arr != null)
                {
                    retList.AddRange(arr);
                }
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return retList;
        }


        public static List<FamilyInfo> SearchFamiliesByVendor(string searchString, int vendorid)
        {

            List<FamilyInfo> retList = new List<FamilyInfo>();
            try
            {
                FamilyInfo[] arr = GetService().SearchFamiliesByVendor(searchString, vendorid);

                if (arr != null)
                {
                    retList.AddRange(arr);
                }
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return retList;
        }

        public static bool GenerateCache(Guid familyId)
        {
            bool success = false;

            try
            {
                success =  GetService().GenerateCache(familyId);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;	
            }

            return success;
        }

        public static bool DeleteCache(Guid familyId)
        {
            bool success = false;

            try
            {
                success = GetService().DeleteCache(familyId);
            }
            catch (System.Exception ex)
            {
            	m_lastErrMsg = ex.Message;
            }

            return success;
        }

        public static Dictionary<string, ParameterInfo> GetModelParameters(string modelPath)
        {
            Dictionary<string, ParameterInfo> retParamList = new Dictionary<string, ParameterInfo>();

            try
            {
                //TODO: Get Model Parameters here from Inventor.
                Byte[] modelData = GetBinaryByPath(modelPath);
                if (modelData != null && modelData.Length > 0)
                {
                    ParameterInfo[] retArr = GetService().GetParameters(modelData);

                    if (retArr == null)
                    {
                        return retParamList;
                    }

                    for (int i = 0; i < retArr.Length; i++)
                    {
                        retParamList.Add(retArr[i].Name, retArr[i]);
                    }
                }
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return retParamList;
        }

        public static bool AddCategory(CategoryInfo newCateInfo)
        {
            bool success = false;

            try
            {
                success = GetService().AddCategory(newCateInfo);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return success;
        }

        public static bool DeleteCategory(Guid cateId)
        {
            bool success = false;

            try
            {
                success = GetService().DeleteCategory(cateId);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return success;
        }

        public static bool UpdateCategory(CategoryInfo cateInfo)
        {
            bool success = false;

            try
            {
                success = GetService().UpdateCategory(cateInfo);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return success;
        }

        public static bool IsFamilyCached(Guid familyId)
        {
            bool success = false;

            try
            {
                success = GetService().IsFamilyCached(familyId);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return success;
        }

        public static FamilyAttrInfo GetFamilyAttrInfo(Guid familyId)
        {
            FamilyAttrInfo retVal = null;

            try
            {
                retVal = GetService().GetFamilyAttrInfo(familyId);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return retVal;
        }

        public static FamilyAttrInfo GetFamilyAttrInfoByType(Guid familyId, FamilyAttrType type)
        {
            FamilyAttrInfo retVal = null;

            try
            {
                retVal = GetService().GetFamilyAttrInfoByType(familyId, type);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return retVal;
        }

        public static DataTable GetSubFamilyTable(Guid familyId, List<ParameterValueInfo> paramConstraints)
        {
            DataTable retVal = null;

            try
            {
                retVal = GetService().GetSubFamilyTable(familyId, paramConstraints.ToArray());
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return retVal;
        }

        public static List<ParameterInfo> GetFamilyParameters(Guid familyId)
        {
            List<ParameterInfo> retVal = null;

            try
            {
                ParameterInfo[] arr = GetService().GetFamilyParameters(familyId);
                retVal = new List<ParameterInfo>();
                retVal.AddRange(arr);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return retVal;
        }

        public static ParameterInfo GetFamilyParameterInfo(Guid familyId)
        {
            ParameterInfo retVal = null;

            try
            {
                retVal = GetService().GetFamilyParameterInfo(familyId);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return retVal;
        }

        public static List<FamilyInfo> GetFamiliesByCategoryId(Guid cateId)
        {
            List<FamilyInfo> retVal = null;

            try
            {
                FamilyInfo[] arr = GetService().GetFamiliesByCategoryId(cateId);
                retVal = new List<FamilyInfo>();
                retVal.AddRange(arr);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return retVal;
        }


        public static List<FamilyInfo> GetFamiliesByCategoryIdnew(Guid cateId,string str,string searchString)
                {
                    List<FamilyInfo> retVal = null;

                    try
                    {
                        FamilyInfo[] arr = GetService().GetFamiliesByCategoryIdnew(cateId,str,searchString);
                        retVal = new List<FamilyInfo>();
                        retVal.AddRange(arr);
                    }
                    catch (System.Exception ex)
                    {
                        m_lastErrMsg = ex.Message;
                    }

                    return retVal;
                }

        public static List<SAImageInfo> GetFamilyImageByFamilies(List<FamilyInfo> familiesInfo)
        {
            List<SAImageInfo> retVal = new List<SAImageInfo>();

            try
            {
                foreach (FamilyInfo item in familiesInfo)
                {
                    Byte[] thumbnailPic = GetService().GetFamilyThumbnailPic(item.ID);

                    SAImageInfo image = new SAImageInfo();
                    image.ImageByte = thumbnailPic;
                    image.Id = item.ID.ToString();
                    image.Name = item.DisplayName;
                    image.Descript = item.Name;
                    image.VendorId = item.VendorID;
                    image.PublishDate = item.PublishDate;
                    retVal.Add(image);
                }
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return retVal;
        }

        public static List<FamilyInfo> GetFamiliesByVendorId(int vendorId, string searchString)
        {
            List<FamilyInfo> retVal = null;

            try
            {
                FamilyInfo[] arr = GetService().GetFamiliesByVendorId(vendorId, searchString);
                retVal = new List<FamilyInfo>();
                retVal.AddRange(arr);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return retVal;
        }

        public static List<FamilyInfo> GetFamiliesByCategoryVendorId(Guid cateId, int vendorId, string searchString,string str)
        {
            List<FamilyInfo> retVal = null;

            try
            {
                FamilyInfo[] arr = GetService().GetFamiliesByCategoryVendorId(cateId, vendorId, searchString,str);
                retVal = new List<FamilyInfo>();
                retVal.AddRange(arr);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return retVal;
        }

        public static FamilyInfo GetFamilyInfo(Guid famiId)
        {
            FamilyInfo retVal = null;
            try
            {
                retVal = GetService().GetFamilyInfo(famiId);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return retVal;
        }

        public static List<FamilyInfo> GetFamiliesByStandardId(int standardId)
        {
            List<FamilyInfo> retVal = null;

            try
            {
                FamilyInfo[] arr = GetService().GetFamiliesByStandardId(standardId);
                retVal = new List<FamilyInfo>();
                retVal.AddRange(arr);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return retVal;
        }

        public static List<ParameterValueInfo> GetDriveParameterVals(Guid familyId, Guid instanceId)
        {
            List<ParameterValueInfo> retVal = null;

            try
            {
                ParameterValueInfo[] arr = GetService().GetDriveParameterVals(familyId, instanceId);
                retVal = new List<ParameterValueInfo>();
                retVal.AddRange(arr);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return retVal;
        }

        public static CategoryInfo GetCategoryInfoByCateId(Guid familyId)
        {
            CategoryInfo retVal = null;

            try
            {
                retVal = GetService().GetCategoryInfoByCateId(familyId);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return retVal;
        }

        public static bool GeneratePart(Page page,Guid familyId, Guid instanceId, List<ParameterInfo> driveParameterInfos, string targetPath)
        {
            Byte[] retVal = null;

            try
            {
                string fileExtension = Path.GetExtension(targetPath);
                retVal = GetService().GeneratePart(familyId, instanceId, driveParameterInfos.ToArray(), fileExtension);
                //targetPath = SaveBinaryByPath(targetPath, retVal);
                DownLoadWebBinary(page,Path.GetFileName(targetPath) ,retVal);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return (retVal != null) ? true : false;
        }

        public static List<ParameterInfo> GetFamilyKeyParameters(Guid familyId)
        {
            List<ParameterInfo> retVal = null;

            try
            {
                ParameterInfo[] arr = GetService().GetFamilyKeyParameters(familyId);
                retVal = new List<ParameterInfo>();
                retVal.AddRange(arr);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return retVal;
        }

        public static List<ParameterValueInfo> GetParamVals(Guid parameterId, List<ParameterValueInfo> paramConstrains)
        {
            List<ParameterValueInfo> retVal = null;

            try
            {
                ParameterValueInfo[] arr = GetService().GetParamVals(parameterId, paramConstrains.ToArray());
                retVal = new List<ParameterValueInfo>();
                retVal.AddRange(arr);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return retVal;
        }

        #region "Vendor methods"
        public static List<VendorInfo> GetAllVendors()
        {
            List<VendorInfo> retVal = null;

            try
            {
                VendorInfo[] arr = SABLL.GetService().GetAllVendors();
                retVal = new List<VendorInfo>();
                retVal.AddRange(arr);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return retVal;
        }

        //public static void InitVendorListView(ListView listView)
        //{
        //    if (listView == null) return;

        //    listView.Clear();

        //    //get all vendors.
        //    VendorInfo[] vendors = SABLL.GetService().GetAllVendors();

        //    if (vendors == null)
        //    {
        //        return;
        //    }

        //    for (int i = 0; i < vendors.Length; i++)
        //    {
        //        VendorInfo curVendorInfo = vendors[i];
        //        ListViewItem newItem = listView.Items.Add(curVendorInfo.Name);
        //        newItem.Tag = curVendorInfo.VendorId;
        //    }
        //}

        //public static void InitVendorComboBoxView(RadComboBox comboBox)
        //{
        //    if (comboBox == null) return;

        //    comboBox.Items.Clear();

        //    //get all vendors.
        //    VendorInfo[] vendors = SABLL.GetService().GetAllVendors();

        //    if (vendors == null)
        //    {
        //        return;
        //    }

        //    for (int i = 0; i < vendors.Length; i++)
        //    {
        //        VendorInfo curVendorInfo = vendors[i];
        //        comboBox.Items.Add(new VendorItem(curVendorInfo));
        //    }
        //}

        public static VendorInfo GetVendorByName(string vendorName)
        {
            VendorInfo retVal = null;

            try
            {
                retVal = GetService().GetVendorByName(vendorName);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return retVal;
        }

        public static VendorInfo GetVendor(int vendorId)
        {
            VendorInfo retVal = null;

            try
            {
                retVal = GetService().GetVendor(vendorId);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return retVal;
        }

        public static bool AddVendor(VendorInfo newVendorInfo)
        {
            bool success = false;

            try
            {
                success = GetService().AddVendor(newVendorInfo);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return success;
        }

        public static bool UpdateVendor(VendorInfo updateVendorInfo)
        {
            bool success = false;

            try
            {
                success = GetService().UpdateVendor(updateVendorInfo);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return success;
        }

        public static bool DeleteVendor(string vendorName)
        {
            bool success = false;

            try
            {
                success = GetService().DeleteVendor(vendorName);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return success;
        }
        #endregion

        
        #region "Standard methods"
        public static List<StandardInfo> GetAllStandards()
        {
            List<StandardInfo> retVal = null;

            try
            {
                StandardInfo[] arr = SABLL.GetService().GetAllStandards();
                retVal = new List<StandardInfo>();
                retVal.AddRange(arr);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return retVal;
        }

        //public static void InitStandardListView(ListView listView)
        //{
        //    if (listView == null) return;

        //    listView.Clear();

        //    //get all standards.
        //    StandardInfo[] standards = SABLL.GetService().GetAllStandards();

        //    if (standards == null)
        //    {
        //        return;
        //    }

        //    for (int i = 0; i < standards.Length; i++)
        //    {
        //        StandardInfo curStandardInfo = standards[i];
        //        ListViewItem newItem = listView.Items.Add(curStandardInfo.Name);
        //        newItem.Tag = curStandardInfo.StandardId;
        //    }
        //}

        //public static void InitStandardComboBoxView(ComboBox comboBox)
        //{
        //    if (comboBox == null) return;

        //    comboBox.Items.Clear();

        //    //get all standards.
        //    StandardInfo[] standards = SABLL.GetService().GetAllStandards();

        //    if (standards == null)
        //    {
        //        return;
        //    }

        //    for (int i = 0; i < standards.Length; i++)
        //    {
        //        StandardInfo curStandardInfo = standards[i];
        //        comboBox.Items.Add(new StandardItem(curStandardInfo));
        //    }
        //}

        public static StandardInfo GetStandardByName(string standardName)
        {
            StandardInfo retVal = null;

            try
            {
                retVal = GetService().GetStandardByName(standardName);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return retVal;
        }

        public static StandardInfo GetStandard(int standardId)
        {
            StandardInfo retVal = null;

            try
            {
                retVal = GetService().GetStandard(standardId);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return retVal;
        }

        public static bool AddStandard(StandardInfo newStandardInfo)
        {
            bool success = false;

            try
            {
                success = GetService().AddStandard(newStandardInfo);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return success;
        }

        public static bool UpdateStandard(StandardInfo updateStandardInfo)
        {
            bool success = false;

            try
            {
                success = GetService().UpdateStandard(updateStandardInfo);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return success;
        }

        public static bool DeleteStandard(string standardName)
        {
            bool success = false;

            try
            {
                success = GetService().DeleteStandard(standardName);
            }
            catch (System.Exception ex)
            {
                m_lastErrMsg = ex.Message;
            }

            return success;
        }
        #endregion
    }
}
